import time

import pytest
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

cases = [['18200553871', 'wyq13542', '登录成功'],
         ['18200553871', 'wyq13522', '错误的密码登录失败']]
driver = None  # 保存浏览器对象


@pytest.mark.parametrize('case', cases)
def test_login(case):
    global driver
    if not driver:
        path = Service('./chromedriver')
        driver = webdriver.Chrome(service=path)
        # 打开豆瓣登录页面
        driver.get('https://accounts.douban.com/passport/login?source=movie')
        time.sleep(2)
        # 定位「密码登录」按钮
        # <li class="account-tab-account">密码登录</li>
        password_login = driver.find_element(By.CLASS_NAME, 'account-tab-account')
        # 点击「密码登录」
        password_login.click()
        time.sleep(2)
    # 定位用户名输入框
    user = driver.find_element(By.ID, 'username')
    # 输入用户名
    user.send_keys(case[0])
    time.sleep(2)
    # 定位密码输入框
    pwd = driver.find_element(By.ID, 'password')
    # 输入密码
    pwd.send_keys(case[1])
    time.sleep(2)
    # 定位「登录」按钮
    button = driver.find_element(By.XPATH, '//*[@id="account"]/div[2]/div[2]/div/div[2]/div[1]/div[4]/a')
    # 点击「登录」
    button.click()
    time.sleep(2)
    if case[-1] == '登录成功':
        page = driver.page_source  # 获取页面源码
        driver.quit()  # 关闭浏览器
        driver = None
        assert '豆友285304728的账号' in page  # 断言登录成功
    else:
        try:
            assert '登录豆瓣' == driver.title  # 断言登录失败
        except Exception:
            raise Exception  # 抛出异常，确保统计结果正确性
        finally:
            driver.refresh()  # 刷新页面

    if case == cases[-1]:
        driver.quit()  # 关闭浏览器


if __name__ == '__main__':
    pytest.main('-v', __file__)
